package fengstyle.sms;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 生产者，发送消息给MQ
 */
@RestController
public class SmsProducerService {

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 异步发送消息
     * @param msg
     */
    @GetMapping("/sms/asyncSend")
    public void snedMsg(String msg){
        Message message = new Message("sms-topic", "sms-tags", msg.getBytes());
        SendCallback callback = new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("异步消息发送成功");
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("异步消息发送失败");
            }
        };
        rocketMQTemplate.asyncSend("sms-topic:async", message, callback);
        System.out.println("发送了异步消息 "+message);
    }

    /**
     * 同步发送消息
     * @param msg
     */
    @GetMapping("/sms/syncSend")
    public void syncSend(String msg){
        Message message = new Message("sms-topic", "sms-tags", msg.getBytes());
        SendResult result = rocketMQTemplate.syncSend("sms-topic:sync", message);
        System.out.println("发送了同步消息 "+message);
        System.out.println("发送了同步消息结果 "+result);
    }

    /**
     * 单向发送消息，只管发送，其他不管
     * @param msg
     */
    @GetMapping("/sms/sendOneWay")
    public void sendOneWay(String msg){
        Message message = new Message("sms-topic", "sms-tags", msg.getBytes());
        rocketMQTemplate.sendOneWay("sms-topic:sendOneWay", message);
        System.out.println("发送了单向消息 "+message);
    }

    /**
     * 发送延迟消息
     * @param msg
     */
    @GetMapping("/sms/sendDelay")
    public void sendDelay(String msg){
        org.springframework.messaging.Message<String> message = MessageBuilder.withPayload(msg).build();
        //RocketMQ并不支持任意时间的延迟，需要设置几个固定的延时等级，从1s到2h共18个等级
        //messageDelayLevel: 1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
        rocketMQTemplate.syncSend("sms-topic:sendDelay", message, 1 * 1000l, 4);
        System.out.println("发送了延时消息 "+message);
    }
}
